package graph.unweighted;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
/**
 * 
 * @Title: AdjacentList.java 
 * @Package graph 
 * @Description: 图论算法的基础类：底层基于TreeSet的邻接表
 *                  有向无权图
 * @author CandyWall   
 * @date 2021年1月14日 下午12:35:12 
 * @version V1.0
 */
public class CandyGraph implements Cloneable, Serializable {
    private int vertex_num; // 当前图中的顶点数
    private int edge_num;   // 当前图中的边数
    private TreeSet<Integer>[] adj;    // 邻接矩阵
    private boolean directed;
    private int[] inDegrees, outDegrees;    // 有向图的入度和出度
    
    /**
     * 从文件中加载一个图
     * @param filename
     * @param directed：是否是有方向的
     */
    public CandyGraph(String filename, boolean directed) {
        this.directed = directed;
        try(Scanner scanner = new Scanner(new File(filename))) {
            // 读取顶点数
            vertex_num = scanner.nextInt();
            if(vertex_num < 0) {
                throw new IllegalArgumentException("顶点数必须是非负数！");
            }
            // 读取边数
            edge_num = scanner.nextInt();
            if(edge_num < 0) {
                throw new IllegalArgumentException("边数必须是非负数！");
            }
            // 初始化邻接表
            adj = new TreeSet[vertex_num];
            for(int i = 0; i < vertex_num; i++) {
                adj[i] = new TreeSet<>();
            }
            
            // 初始化记录顶点的入度和出度数组
            if(directed) {
                inDegrees = new int[vertex_num];
                outDegrees = new int[vertex_num];
            }
            
            // 读取边各个边
            for(int i = 0; i < edge_num; i++) {
                int a = scanner.nextInt();
                validateVertex(a);
                int b = scanner.nextInt();
                validateVertex(b);
                if(a == b) {
                    throw new IllegalArgumentException("检测到了自环边！");
                }
                if(adj[a].contains(b)) {
                    throw new IllegalArgumentException("检测到了平行边！");
                }
                adj[a].add(b);
                // 如果是无向图，默认a和b之间相互连通
                if(!directed) {
                    adj[b].add(a);
                } 
                // 如果是有向图，计算顶点的入度和出度
                else {
                    inDegrees[b]++;     
                    outDegrees[a]++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("边数少于指定的值！");
        }
    }
    
    public CandyGraph(String filename) {
        this(filename, false);
    }
    
    public CandyGraph(int vertex_num, boolean directed) {
        this.vertex_num = vertex_num;
        this.directed = directed;
        this.edge_num = 0;
        this.adj = new TreeSet[vertex_num];
        for(int i = 0; i < vertex_num; i++) {
            this.adj[i] = new TreeSet<>();
        }
        
        this.edge_num++;
    }
    
    public void addEdge(int a, int b) {
        validateVertex(a);
        validateVertex(b);
        if(a == b) {
            throw new IllegalArgumentException("检测到了自环边！");
        }
        if(adj[a].contains(b)) {
            throw new IllegalArgumentException("检测到了平行边！");
        }
        
        adj[a].add(b);
        if(!directed) {
            adj[b].add(a);
        }
    }
    
    public CandyGraph(TreeSet<Integer>[] adj, boolean directed) {
        this.adj = adj;
        this.directed = directed;
        this.vertex_num = adj.length;
        this.edge_num = 0;
        this.inDegrees = new int[this.vertex_num];
        this.outDegrees = new int[this.vertex_num];
        for(int v = 0; v < this.vertex_num; v++) {
            for(int w : adj[v]) {
                this.edge_num++;
                this.outDegrees[v]++;
                this.inDegrees[w]++;
            }
        }
        // 如果是无向图，边数需要除2
        if(!directed) {
            this.edge_num /= 2;
        }
    }
    
    /**
     *  判断顶点是否合法
     * @param v
     */
    public void validateVertex(int v) {
        if(v < 0 || v >= vertex_num) {
            throw new IllegalArgumentException("顶点" + v + "不合法！");
        }
    }
    
    public boolean isDirected() {
        return directed;
    }

    /**
     *  获取顶点数
     * @return
     */
    public int getVertex_num() {
        return vertex_num;
    }

    /**
     *  获取边数
     * @return
     */
    public int getEdge_num() {
        return edge_num;
    }
    
    /**
     * 判断顶点1和顶点2之间是否有一条边
     * @param v
     * @param w
     * @return
     */
    public boolean hasEdge(int v, int w) {
        validateVertex(v);
        validateVertex(w);
        return adj[v].contains(w);
    }
    
    /**
     * 删除顶点v和w之间的一条边
     * @param v
     * @param w
     */
    public void removeEdge(int v, int w) {
        validateVertex(v);
        validateVertex(w);
        if(adj[v].remove(w)) {
            edge_num--;
            if(directed) {
                inDegrees[w]--;
                outDegrees[v]--;
            }
        }
        if(!directed) {
            adj[w].remove(v);
        }
    }
    
    /**
     * 返回和某个顶点相邻的所有顶点
     * @param v
     * @return
     */
    public Iterable<Integer> adjacentVertexes(int v) {
        validateVertex(v);
        return adj[v];
    }
    
    /**
     * 返回一个无向图顶点的度
     * @param v
     * @return
     */
    public int getDegree(int v) {
        if(directed) {
            throw new IllegalArgumentException("getDegree()方法只能用于无向图中！");
        }
        validateVertex(v);
        return adj[v].size();
    }
    
    /**
     * 求一个顶点的入度
     * @param v
     * @return
     */
    public int getInDegree(int v) {
        if(!directed) {
            throw new IllegalArgumentException("getInDegree()方法只能用于有向图中！");
        }
        validateVertex(v);
        return inDegrees[v];
    }
    
    /**
     * 求一个顶点的出度
     * @param v
     * @return
     */
    public int getOutDegree(int v) {
        if(!directed) {
            throw new IllegalArgumentException("getInDegree()方法只能用于有向图中！");
        }
        validateVertex(v);
        return outDegrees[v];
    }
    
    /**
     * 获取将有向图的边的方向反过来之后的图
     * @return
     */
    public CandyGraph reverseGraph() {
        TreeSet<Integer>[] reversedAdj = new TreeSet[vertex_num];
        for(int i = 0; i < vertex_num; i++) {
            reversedAdj[i] = new TreeSet<>();
        }
        for(int v = 0; v < vertex_num; v++) {
            for(int w : adjacentVertexes(v)) {
                reversedAdj[w].add(v);
            }
        }
        
        return new CandyGraph(reversedAdj, directed);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(String.format("顶点数  = %d，边数 = %d，" + (directed ? "有向图" : "无向图") + "\n", vertex_num, edge_num));
        sb.append("  ");
        for(int i = 0; i < vertex_num; i++) {
            sb.append(i + " ");
        }
        sb.append('\n');
        for(int v = 0; v < vertex_num; v++) {
            // 打印行下标
            sb.append(v + " ");
            for(int w : adj[v]) {
                sb.append(w + " ");
            }
            sb.append('\n');
        }
        return sb.toString();
    }

    @Override
    /*protected Object clone() {
        CandyGraph graph = null;
        try {
            graph = (CandyGraph) super.clone();
            graph.adj = new TreeSet[adj.length];
            for(int v = 0; v < graph.getVertex_num(); v++) {
                graph.adj[v] = new TreeSet<>();
                for(int w : adj[v]) {
                    graph.adj[v].add(w);
                }
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        
        return graph;
    }*/
    public Object clone() {
        Object clonedGraph = null;
        try {
            // 将当前对象写入字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.close();
            // 分配内存，写入原始对象，生成新对象
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            clonedGraph = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return clonedGraph;
    }

    public static void main(String[] args) {
        CandyGraph graph = new CandyGraph("testData/directed/unweightedGraph.txt", true);
        // 打印邻接矩阵，验证图是否被正确保存
        //adjacentMatrix.printAdj();
        System.out.println(graph);
        System.out.print("1的邻边有：");
        System.out.println(graph.adjacentVertexes(1));
        System.out.println(graph.hasEdge(0, 1));
        System.out.println(graph.hasEdge(0, 2));
        for(int v = 0; v < graph.getVertex_num(); v++) {
            System.out.println(v + ": " + graph.getInDegree(v) + " " + graph.getOutDegree(v));
        }
    }
}
